<?php
namespace app\api\controller;
use app\common\controller;
class Pbook extends controller\ApiCommon
{

	public function _initialize() {
		$this->uid = $_COOKIE['USER_ID'];
	}
	public function isauto(){
		$uid = $this->uid;
		if($uid){
			return true;
		}else{
			return false;
		}
	}
	/*
	 * 登录
	 */
	public function doLogin(){
		$request = file_get_contents('php://input');
		$request = json_decode($request,1);
		if($request['mobile']&&$request['pass']){
			$user = db('books_members')->where(array('mobile'=>$request['mobile']))->find();
			if($user){
				if(sp_compare_password($request['pass'],$user['pass'])){
					setcookie("USER_ID",$user['uid'],time()+3156000);
					$return['code'] = 200;
				}else{
					$return['code'] = 40002;
					$return['msg'] = '密码错误';
				}
			}else{
				$return['code'] = 40001;
				$return['msg'] = '用户不存在,请注册';
			}
		}else{
			$return['code'] = 40000;
			$return['msg'] = '参数为空';
		}
		ret_json($return);
	}
	/*
	 * 获取用户信息
	 */
	public function getUserInfo(){
		$uid = $this->uid;
		if($uid){
			$userinfo = db('books_members')->where(array('uid'=>$uid))->find();
			if($userinfo){
				setcookie("USER_ID",$userinfo['uid'],time()+3156000);
			}
		}else{
			$userinfo = 0;
		}
		ret_json($userinfo);
	}
	/*
	 * 保存当前阅读章节
	 */
	public function setNewTap(){
		$uid = $this->uid;
		$request = file_get_contents('php://input');
		$request = json_decode($request,1);
		if($request['cid']&&$request['tap']){
			$issc = db('books_collect')->where(array('uid'=>$this->uid,'bid'=>$request['cid']))->find();
			if($issc){
				$data['tap'] = $request['tap'];
				$data['taptime'] = time();
				$data['ntime'] = time();
				$data['ntitle'] = db('books_chapter')->where(array('id'=>$request['tap']))->column('title');
				db('books_collect')->where(array('id'=>$issc['id']))->update($data);
			}else{
				$data['uid'] = $uid;
				$data['bid'] = $request['cid'];
				$data['tap'] = $request['tap'];
				$data['taptime'] = time();
				$data['ntime'] = time();
				$data['ntitle'] = db('books_chapter')->where(array('id'=>$request['tap']))->column('title');
				$data['time'] = time();
				db('books_collect')->insert($data);
			}
		}else{
			$return['code'] = 40000;
			$return['msg'] = '参数为空';
		}
		ret_json($return);
	}
	/*
	 * 获取收藏列表
	 */
	public function getBookList(){
		$list = db('books_collect')->field('b.name,b.img,a.nstatus,a.ntitle,a.ntime,a.bid')->alias('a')->join('__BOOKS_TBOOK__ b',"b.id=a.bid")->where(array('a.uid'=>$this->uid,'a.status'=>1))->order('a.taptime desc')->select();
		foreach ($list as &$v){
			$t = time()-$v['ntime'];
			switch ($t){
				case $t<60:
					$v['ntime'] = $t.'秒前';
					break;
				case $t<3600:
					$v['ntime'] = ceil($t/60).'分钟前';
					break;
				case $t<86400:
					$v['ntime'] = ceil($t/3600).'小时前';
					break;
				case $t>86400:
					$v['ntime'] = ceil($t/86400).'天前';
					break;
			}
		}
		$return['data'] = $list;
		ret_json($return);
	}
	/*
	 * 搜索
	 */
	public function getSearchList(){
		set_time_limit(0);
		$request = file_get_contents('php://input');
		$request = json_decode($request,1);
		$name = $request['name'];
		if(empty($name)){
			ret_json(array('code'=>40000,'msg'=>'书名为空'));
		}
		$tbook = db('books_tbook')->where('name','like',$name.'%')->select();
		if($tbook){
			foreach ($tbook as &$v){
				$v['gourl'] = url('getBookChapter',array('bid'=>$v['id']));
				$v['img'] = $v['img'];
			}
			ret_json(array('code'=>200,'data'=>$tbook));
		}else{
			$arr = array(
				'1'=>'img',
				'2'=>'url',
				'3'=>'name',
				'4'=>'intro',
				'5'=>'writer',
			);
			$bsite = db('books_site')->where('status','eq','1')->select();
			foreach ($bsite as $b){
				$list = getCurlList($b['serach_url'].$name);
				//$b['tbook_regular'] = '#<div class="result-item result-game-item">.*<img src="(.*)".*<a cpos="title" href="(.*)".*title="(.*)".*<p class="result-game-item-desc">(.*)</p>.*<span class="result-game-item-info-tag-title preBold">.*<span>(.*)</span>#isU';
				$reg = $b['tbook_regular'];
				header("Content-type: text/html; charset=utf-8");
				preg_match($reg, $list, $matchs);
				$list = getPregMatch($reg,$list,0);
				foreach ($list[1] as $k=>&$v){
					if($list[3][$k] == $name){
						$img = db('books_img')->where(array('site'=>$b['id'],'url'=>$v))->find();
						if($img){
							$v = $img['img'];
						}else{
							if($b['is_https'] == 1&&substr($v,5)!='https'){
								$v = substr_replace($v,'https',0,4); 
							}
							$ext = get_extension($v);
							$img = './public/images/'.time().$b['id'].rand(1,1000).'.'.$ext;
							http_down($v,$img);
							$imgInfo['site'] = $b['id'];
							$imgInfo['url'] = $v;
							$imgInfo['img'] = $img;
							db('books_img')->insert($imgInfo);
							$v = $img;
						}
					}else{
						unset($list[1][$k]);
					}
				}
				$arrays = array();
				for($i=0;$i<count($list[1]);$i++){
					$array = array();
					$array['img'] = getInurl().$list[1][$i];
					$array['url'] = $list[2][$i];
					$array['name'] = $list[3][$i];
					$array['intro'] = $list[4][$i];
					$array['writer'] = trim($list[5][$i]);
					$book = db('books_tbook')->where(array('site_id'=>$b['id'],'writer'=>$array['writer'],'name'=>$array['name']))->find();
					if(!$book){
						$array['site_id'] = $b['id'];
						$array['time'] = time();
						$bid = db('books_tbook')->insertGetId($array);
						$array['id'] = $bid;
					}else{
						$array['id'] = $book['id'];
					}
					$array['gourl'] = url('getBookChapter',array('bid'=>$array['id']));
					$arrays[$i] = $array;
				}
				ret_json(array('code'=>200,'data'=>$arrays));
			}
		}
	}
	/*
	 * 获取详情
	 */
	public function getBookInfo(){
		set_time_limit(0);
		$request = file_get_contents('php://input');
		$request = json_decode($request,1);
		$cid = $request['cid'];
		$uid = $this->uid;
		$readsta = db('books_collect')->where(array('uid'=>$this->uid,'bid'=>$cid))->find();
		if($readsta){
			$books = db('books_chapter')->where(array('id'=>array('>=',$readsta['tap'])))->limit('5')->field('id,book_detail,title,url')->select();
		}else{
			$books = db('books_chapter')->where(array('bid'=>$cid))->limit('5')->field('id,book_detail,title,url')->select();
		}
		if($books){
			$prepsta = db('books_chapter')->where(array('id'=>array('<',$books[0]['id']),'bid'=>$cid))->find();
			$lend = count($books);
			$nextsta = db('books_chapter')->where(array('id'=>array('>',$books[$lend-1]['id']),'bid'=>$cid))->find();
			$prepsta = $prepsta?1:0;
			$nextsta = $nextsta?1:0;
			$tbook = db('books_tbook')->where(array('id'=>$cid))->find();
			$bsite = db('books_site')->where(array('id'=>$tbook['site_id']))->find();
			foreach($books as &$v){
				if(empty($v['book_detail'])){
					$list = file_get_contents($v['url']);
					$reg = $bsite['detail_regular'];
					header("Content-type: text/html; charset=utf-8");
					$list = getPregMatch($reg,$list,1);
					$datas['book_detail'] = $list[1];
					db('books_chapter')->where(array('id'=>$v['id']))->update($datas);
					$v['book_detail'] = $list[1];
				}
				//$v['book_detail'] = delHtmlIco($v['book_detail']);
			}
			$return['data'] = $books;
			$return['nextsta'] = $nextsta;
			$return['prepsta'] = $prepsta;
			return json($return);
		}else{
			$tbook = db('books_tbook')->where(array('id'=>$cid))->find();
			$bsite = db('books_site')->where(array('id'=>$tbook['site_id']))->find();
			if($bsite['is_https'] == 1&&substr($tbook['url'],5)!='https'){
				$tbook['url'] = substr_replace($tbook['url'],'https',0,4); 
			}
			$bsite['chapter_regular'] = '#<dd> <a style="" href="(.*)">(.*)</a></dd>#isU';
			$list = file_get_contents($tbook['url']);
            //$list = getCurlList($tbook['url']);
            //$b['tbook_regular'] = '#<div class="result-item result-game-item">.*<img src="(.*)".*<a cpos="title" href="(.*)".*title="(.*)".*<p class="result-game-item-desc">(.*)</p>.*<span class="result-game-item-info-tag-title preBold">.*<span>(.*)</span>#isU';
            $reg = $bsite['chapter_regular'];
            header("Content-type: text/html; charset=utf-8");
            $list = getPregMatch($reg,$list,0);
            $datas = array();
            for($i=0;$i<count($list[1]);$i++){
                $array = array();
                $array['url'] = $bsite['url'].$list[1][$i];
                $array['title'] = $list[2][$i];
                $array['bid'] = $cid;
                $datas[] = $array;
            }
            db('books_chapter')->insertAll($datas);
			$chapter = db('books_chapter')->where(array('bid'=>$cid))->limit('5')->select();
			foreach($chapter as &$v){
				if(empty($v['book_detail'])){
					$list = file_get_contents($v['url']);
					$reg = $bsite['detail_regular'];
					header("Content-type: text/html; charset=utf-8");
					$list = getPregMatch($reg,$list,1);
					$datas_d['book_detail'] = $list[1];
					db('books_chapter')->where(array('id'=>$v['id']))->update($datas_d);
					$v['book_detail'] = $list[1];
				}
			}
			$prepsta = db('books_chapter')->where(array('id'=>array('<',$chapter[0]['id']),'bid'=>$cid))->find();
			$lend = count($chapter);
			$nextsta = db('books_chapter')->where(array('id'=>array('>',$chapter[$lend-1]['id']),'bid'=>$cid))->find();
			$prepsta = $prepsta?1:0;
			$nextsta = $nextsta?1:0;
			$return['data'] = $chapter;
			$return['nextsta'] = $nextsta;
			$return['prepsta'] = $prepsta;
			return json($return);
		}
	}
	/*
	 * 获取章节
	 */
	public function getBookChapter(){
		set_time_limit(0);
		$request = file_get_contents('php://input');
		$request = json_decode($request,1);
		$cid = $request['cid'];
		$list = db('books_chapter')->where(array('bid'=>$cid))->field('id,title')->select();
		$return['data'] = $list;
		ret_json($return);
	}
	/*
	 * 获取下一批
	 */
	public function getNextBookInfo(){
		$request = file_get_contents('php://input');
		$request = json_decode($request,1);
		$cid = $request['cid'];
		$tap = $request['tap'];
		$uid = $this->uid;
		$type = $request['type'];
		if($type != 1){
			if($request['isnow']){
				$where['id'] = array('<=',$tap);
			}else{
				$where['id'] = array('<',$tap);
			}
			$books = db('books_chapter')->where($where)->limit('5')->order('id desc')->field('id,book_detail,title,url')->select();
			$books = array_reverse($books);
			$prepsta = db('books_chapter')->where(array('id'=>array('<',$books[0]['id']),'bid'=>$cid))->find();
			$lend = count($books);
			$nextsta = db('books_chapter')->where(array('id'=>array('>',$books[$lend-1]['id']),'bid'=>$cid))->find();
			$prepsta = $prepsta?1:0;
			$nextsta = $nextsta?1:0;
		}else{
			if($request['isnow']){
				$where['id'] = array('>=',$tap);
			}else{
				$where['id'] = array('>',$tap);
			}
			$books = db('books_chapter')->where($where)->limit('5')->field('id,book_detail,title,url')->select();
			$prepsta = db('books_chapter')->where(array('id'=>array('<',$books[0]['id']),'bid'=>$cid))->find();
			$lend = count($books);
			$nextsta = db('books_chapter')->where(array('id'=>array('>',$books[$lend-1]['id']),'bid'=>$cid))->find();
			$prepsta = $prepsta?1:0;
			$nextsta = $nextsta?1:0;
		}
		$tbook = db('books_tbook')->where(array('id'=>$cid))->find();
		$bsite = db('books_site')->where(array('id'=>$tbook['site_id']))->find();
		foreach($books as &$v){
			if(empty($v['book_detail'])){
				$list = file_get_contents($v['url']);
				$reg = $bsite['detail_regular'];
				header("Content-type: text/html; charset=utf-8");
				$list = getPregMatch($reg,$list,1);
				$datas['book_detail'] = $list[1];
				db('books_chapter')->where(array('id'=>$v['id']))->update($datas);
				$v['book_detail'] = $list[1];
			}
			//$v['book_detail'] = delHtmlIco($v['book_detail']);
		}
		$return['data'] = $books;
		$return['prepsta'] = $prepsta;
		$return['nextsta'] = $nextsta;
		return json($return);
	}
	/*
	 * 获取发送短信验证
	 */
	public function getSmsCheck(){
		
	}
	/*
	 * 发送短信
	 */
	public function sendSms(){

	}
	/*
	 * 注册
	 */
	public function doRegister(){
		$request = file_get_contents('php://input');
		$request = json_decode($request,1);
		$user = db('books_members')->where(array('mobile'=>$request['mobile']))->find();
		if($user){
			$return['code'] = 40000;
			$return['msg'] = '用户已存在';
			ret_json($return);
		}
		$pass = sp_password($request['pass']);
		$data['pass'] = $pass;
		$data['mobile'] = $request['mobile'];
		$uid = db('books_members')->insertGetId($data);
		if($uid){
			setcookie("USER_ID",$uid,time()+3156000);
			$return['code'] = 200;
		}else{
			$return['code'] = 40000;
			$return['msg'] = '系统繁忙，请稍后再试!';
		}
		ret_json($return);
	}
}